package csm.web.core.search.mashup.naver;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import csm.common.StringUtil;
import csm.common.net.HttpRequester;
import csm.web.core.RequestHelper;
import csm.web.core.search.ISearchCommand;
import csm.web.core.search.MashupItem;
import csm.web.core.search.MashupItemList;
import csm.web.core.search.SearchResultInfo;

public class NaverSearchCommand implements ISearchCommand{

	@Override
	public SearchResultInfo doSearch(RequestHelper req) {
		String key = "";
		String uri = "";
		String query = ""; // 검색 질의
		String keyword =""; // 질의어 중에서 검색어 부분
		String searchField = ""; // 질의어 중에서 검색필드 부

		String startRow = "1";    // 검색 결과 문서 중, 문서의 시작점을 의미
		String displayRowCount = "10"; // pagesize
		String target = "book";
		String targetEncoding = ""; // 파마메터 인코딩
		String apiUrl =""; // '더보기' 했을때 이동할 사이트 URL


		String mashupId = req.getParameter("mashup_id");
		MashupItem itm = MashupItemList.getInstance().getItem(mashupId);
		if(itm == null)
		    return new NaverSearchResult();

		key = itm.getApiKey();
		uri = itm.getApiBaseUri();
		apiUrl = itm.getApiUrl(); // 더보기 했을때 이동할 사이트 url

		// 네이버에선 검색영역을 구분한다.
		target = itm.getDefaultParam();
		if(StringUtil.isNullOrEmpty(target))
			return new  NaverSearchResult();

		// 요청쿼리의 URLEncoding. 값이 없다면 WAS의 설정을 따르게 된다.
		targetEncoding = itm.getRequestEncoding();
		targetEncoding = StringUtil.isNullOrEmpty(targetEncoding) ? "" : targetEncoding;


		keyword = req.getParameter("keyword");
		if( StringUtil.isNullOrEmpty(keyword))
			return new  NaverSearchResult();

		String[] keywords = StringUtil.split(keyword, ":");
		if(keywords == null )
			return new  NaverSearchResult();

		try {
			if (keywords.length == 1) {
				searchField = "";
				query = keyword;
				if( !StringUtil.isNullOrEmpty(targetEncoding))
					query = URLEncoder.encode(query, targetEncoding);

			} else {
				searchField = StringUtil.split(keyword, ":")[0];
				query = StringUtil.split(keyword, ":")[1];
				if (!StringUtil.isNullOrEmpty(targetEncoding))
					query = URLEncoder.encode(query, targetEncoding);
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			if (keywords.length == 1) {
				query = keyword;
			} else {
				searchField = StringUtil.split(keyword, ":")[0];
				query = StringUtil.split(keyword, ":")[1];
			}
		}

		HttpRequester hq = new HttpRequester();
		hq.setConnectTimeout(10000);
		hq.setReadTimeout(20000);
		hq.appendParameter("key", key);

		hq.appendParameter("query", query);
		if( target.equalsIgnoreCase("book_adv")){
			if(searchField.equalsIgnoreCase("isbn")){
				hq.appendParameter("d_isbn", query);
			}
			else{
				hq.appendParameter("d_title", query);
			}
		}
		hq.appendParameter("target", target);
		hq.appendParameter("start", startRow);
		hq.appendParameter("display", displayRowCount);

		String cmd = hq.getParameterQuery();
		SearchResultInfo result = new  NaverSearchResult();
		try {

			System.out.println("Naver Mashup Search CMD[" + itm.getDisplayTitle() + "]:" + uri + "?" + cmd);
			String resultXml = hq.executeString(uri + "?" + cmd);

			//System.out.println(resultXml);
			//System.out.println(apiUrl);

			result.parseResult(resultXml);
			result.setEngineQuery(cmd);
			if( !StringUtil.isNullOrEmpty(apiUrl))
				result.setWebPageUrl(StringUtil.replace(apiUrl, "[SEARCH_WORD]", keyword));


			if(result.isRaisedError()){
				System.out.println(result.getErrorMessage());
			}
			//result.setPage(Integer.parseInt(start));
			//result.setPageSize(Integer.parseInt(display));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
